#!/usr/local/bin/python

import os
import sys
os.environ['DJANGO_SETTINGS_MODULE']='settings'
sys.path.append('/usr/local/Django')
sys.path.append('/home/bsft08/51158405/www/blog/api')
sys.path.append('./')
import urllib
import urllib2
from xml.dom import minidom
from xml.dom.minidom import Document
from time import localtime, strftime
import uuid
from django.http import HttpResponse
from django.template import Context
from django.template.loader import get_template

''' postObject
    class for post object
'''
class postObject(object):
    def __init__(self, id, author, update, title, content, postrate):
        self.id = id
        self.author = author
        datetime = update.split('T')
        time = datetime[1].split('.')
        self.update = datetime[0] + ' ' + time[0]
        self.title = title
        self.content = content
        self.postrate = postrate
        

''' commentObject
    class for comment object
'''
class commentObject(object):
    def __init__(self, id, user, time, content, rate):
        self.id = id;
        self.user = user;
        self.time = time;
        self.content = content;
        self.rate = rate;
        

''' getSinglePost
    use Django template
    retrieve a single post and the comments
'''
def getSinglePost(req, **kwargs):
    if 'id' in kwargs.keys():
        postid = kwargs['id']
    username = '51158405'
    passwd = 'dish night word sent'
    blogurl = 'http://www.cs.cityu.edu.hk/~cs4380/webservice/blog/getPost.py'
    # setup the password
    password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
    password_manager.add_password(None, 'http://www.cs.cityu.edu.hk/', username, passwd)
    auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)
    # call the webservice
    params = urllib.urlencode({
        'id': postid,
        'type': 'xml'
    })
    data = urllib2.urlopen(blogurl, params).read()

    # get post data
    xmldoc = minidom.parseString(data)
    posts = xmldoc.getElementsByTagName("entry")
    for post in posts:
        author = getText(post.getElementsByTagName('author')[0].childNodes)
        update = getText(post.getElementsByTagName('updated')[0].childNodes)
        title = getText(post.getElementsByTagName('title')[0].childNodes)
        content = getText(post.getElementsByTagName('content')[0].childNodes)
        postrate = getRate(postid)
        model_post = postObject(postid, author, update, title, content, postrate)
    # get comments data
    model_comment = []
    comment_xml = minidom.parseString(getCommentXML(postid,'xml'))
    comments = comment_xml.getElementsByTagName("comment")
    for comment in comments:
        cid = getText(comment.getElementsByTagName('cid')[0].childNodes)
        user = getText(comment.getElementsByTagName('user')[0].childNodes)
        time = getText(comment.getElementsByTagName('time')[0].childNodes)
        content = getText(comment.getElementsByTagName('content')[0].childNodes)
        rate = getRate(cid)
        model_comment.append(commentObject(cid, user, time, content, rate))
    # get template and render html
    t = get_template('singleBlog.html')
    html = t.render(Context({"post":model_post, "comments":model_comment}))
    return html


def getRate(id):
    rate = ''
    url = 'http://cs4380.cs.cityu.edu.hk/51839597/webservice/getRate.py?type=xml&id=' + id
    file = urllib.urlopen(url)
    # check if data is contains rate value
    if file.readline() == 'ID NOT FOUND\n':
        return 0;
    data = file.read()
    xmldoc = minidom.parseString(data)
    file.close()
    postrate = xmldoc.getElementsByTagName("postrate")[0]
    rate = (getText(postrate.getElementsByTagName('rate')[0].childNodes)).strip()
    #count = getText(postrate.getElementsByTagName('counter')[0].childNodes)
    return rate.split('.')[0]
    

# not in use
def addRate(pid, cid, rate):
    # can add rate from javascript
    url = 'http://cs4380.cs.cityu.edu.hk/51839597/webservice/ratePost.py?id=' + pid + '&rate=' + rate
    data = urllib.urlopen(url).read()
    url = 'http://cs4380.cs.cityu.edu.hk/51839597/webservice/ratePost.py?id=' + cid + '&rate=' + rate
    data = urllib.urlopen(url).read()
    

''' proxyBlog
    as documented
'''
def proxyBlog(req, **kwargs):
    # get request parameters
    if 'method' in kwargs.keys():
        callmethod = kwargs['method']
    else:
        return "MUST SPECIFY CALLMETHOD"
    
    # your username and password for the blog service
    username = '51158405'
    passwd   = 'dish night word sent'
    blogurl  = 'http://www.cs.cityu.edu.hk/~cs4380/webservice/blog/' + callmethod + '.py'
    
    # setup the password
    password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
    password_manager.add_password(None, 'http://www.cs.cityu.edu.hk/', username, passwd)
    auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)
    
    # setup the parameters for calling the web service
    paramslist = {}
    for key in kwargs.keys():
      if not (key == "method"):
        paramslist[key] = kwargs[key]
    
    params = urllib.urlencode(paramslist)
    
    # call the webservice
    data = urllib2.urlopen(blogurl, params).read()
    return data


''' getPosts
    get data of posts of an user
'''
def getPosts(req, **kwargs):    
    # your username and password for the blog service
    username = '51158405'
    passwd   = 'dish night word sent'
    blogurl  = 'http://www.cs.cityu.edu.hk/~cs4380/webservice/blog/getPost.py'
    
    # setup the password
    password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
    password_manager.add_password(None, 'http://www.cs.cityu.edu.hk/', username, passwd)
    auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)
    
    # setup the parameters for calling the web service
    paramslist = {}
    for key in kwargs.keys():
        paramslist[key] = kwargs[key]    
    params = urllib.urlencode(paramslist)
    
    # call the webservice
    data = urllib2.urlopen(blogurl, params).read()
    return data


''' getBloggers
    return list of bloggers from the system
'''
def getBloggers(req, **kwargs):
    # your username and password for the blog service
    username = '51158405'
    passwd   = 'dish night word sent'
    blogurl  = 'http://www.cs.cityu.edu.hk/~cs4380/webservice/blog/getBlogs.py'
    
    # setup the password
    password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
    password_manager.add_password(None, 'http://www.cs.cityu.edu.hk/', username, passwd)
    auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)
    
    # setup the parameters for calling the web service
    paramslist = {}
    for key in kwargs.keys():
        paramslist[key] = kwargs[key]
    params = urllib.urlencode(paramslist)
    
    # call the webservice
    data = urllib2.urlopen(blogurl, params).read()
    return data


''' createPost
    pass data to createPost webservice
'''
def createPost(req, **kwargs):
    # get request parameters
    username = ''
    passwd = ''
    title = ''
    content = ''
    if 'username' in kwargs.keys():
        username = kwargs['username']
    if 'password' in kwargs.keys():
        passwd = kwargs['password']
    if 'title' in kwargs.keys():
        title = kwargs['title']
    if 'content' in kwargs.keys():
        content = kwargs['content']
    
    blogurl  = 'http://www.cs.cityu.edu.hk/~cs4380/webservice/blog/createPost.py'
    
    # setup the password
    password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
    password_manager.add_password(None, 'http://www.cs.cityu.edu.hk/', username, passwd)
    auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)
    
    # setup the parameters for calling the web service
    params = urllib.urlencode({
      'title': title, 
      'content': content
    })
    
    # call the webservice
    data = urllib2.urlopen(blogurl, params).read()
    return data


''' editPost
    pass data to editPost webservice
'''
def editPost(req, **kwargs):
    # get form variables
    id = ''
    username = ''
    passwd = ''
    title = ''
    content = ''
    if 'id' in kwargs.keys():
        id = kwargs['id']
    if 'author' in kwargs.keys():
        username = kwargs['author']
    if 'password' in kwargs.keys():
        passwd = kwargs['password']
    if 'title' in kwargs.keys():
        title = kwargs['title']
    if 'content' in kwargs.keys():
        content = kwargs['content']
    
    # your username and password for the blog service
    blogurl  = 'http://www.cs.cityu.edu.hk/~cs4380/webservice/blog/editPost.py'
    
    # setup the password
    password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
    password_manager.add_password(None, 'http://www.cs.cityu.edu.hk/', username, passwd)
    auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)
    
    # setup the parameters for calling the web service
    paramslist = {
      'id': id,
      'title': title,
      'content': content
    }   
    params = urllib.urlencode(paramslist)
    
    # call the webservice
    data = urllib2.urlopen(blogurl, params).read()
    #return data
    

''' deletePost
    pass data to deletePost webservice
'''
def deletePost(req, **kwargs):
    # get form variables
    id = ''
    username = ''
    passwd = ''
    title = ''
    content = ''
    if 'id' in kwargs.keys():
        id = kwargs['id']
    if 'author' in kwargs.keys():
        username = kwargs['author']
    if 'password' in kwargs.keys():
        passwd = kwargs['password']
    
    # your username and password for the blog service
    blogurl  = 'http://www.cs.cityu.edu.hk/~cs4380/webservice/blog/deletePost.py'
    
    # setup the password
    password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
    password_manager.add_password(None, 'http://www.cs.cityu.edu.hk/', username, passwd)
    auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
    opener = urllib2.build_opener(auth_handler)
    urllib2.install_opener(opener)
   
    # setup the parameters for calling the web service
    paramslist = {
      'id': id
    }   
    params = urllib.urlencode(paramslist)
    
    # call the webservice
    data = urllib2.urlopen(blogurl, params).read()
    #return data
    

''' getText
    get text in xml node
'''
def getText(nodelist):
    rc = []
    for node in nodelist:
        if node.nodeType == node.TEXT_NODE:
            rc.append(node.data)
    return ''.join(rc)


''' getUsername
    get username from id
'''
def getUsername(req, **kwargs):    
    file = open('/home/bsft08/51158405/www/blog/api/user.xml', 'r')
    #file = urllib2.urlopen('http://cs4380.cs.cityu.edu.hk/51158405/blog/api/user.xml')
    data = file.read()
    file.close() 
    xmldoc = minidom.parseString(data)

    # get form variables (if desired)
    uid = ''
    if 'id' in kwargs.keys():
        uid = kwargs['id']
    
    name = ''
    users = xmldoc.getElementsByTagName("user")
    for user in users:
        _id = getText(user.getElementsByTagName("id")[0].childNodes)
        print _id
        if uid == _id:
            name = getText(user.getElementsByTagName("name")[0].childNodes)
    return name


''' getCommentXML
    return xml or json type of comments of a post
'''
def getCommentXML(pid, type):
    file = open('/home/bsft08/51158405/www/blog/api/comment.xml', 'r')
    #file = urllib2.urlopen('http://cs4380.cs.cityu.edu.hk/51158405/blog/api/comment.xml')
    data = file.read()
    file.close()    
    xmldoc = minidom.parseString(data)
        
    posts = xmldoc.getElementsByTagName("post")
    doc = Document()
    exist = 'false'
    for post in posts:
        _id = getText(post.getElementsByTagName("id")[0].childNodes)
        if pid == _id:
            # retrieve the data of comment post
            exist = 'true'
            comments = post.getElementsByTagName("comment")
            break
            
    if type == 'json':
        result = '{"Comments":['
        if exist == 'true':
            for comment in comments:
                result += '{"author" : "%s", ' % getText(comment.getElementsByTagName('user')[0].childNodes)
                result += '"time" : "%s", ' % getText(comment.getElementsByTagName('time')[0].childNodes)
                result += '"content" : "%s"}' % getText(comment.getElementsByTagName('content')[0].childNodes)
        result += ']}'
        return result
        
    else: # xml format
        if exist == 'true':
            result = doc.createElement('Comments')
            for comment in comments:
                result.appendChild(comment)
            return result.toxml()
        else:
            return '<Comments></Comments>'
 

''' getComment
    pass data from url parameters and return comment data
''' 
def getComment(req, **kwargs):    
    # get form variables (if desired)
    pid = ''
    type = ''    
    if 'id' in kwargs.keys():
        pid = kwargs['id']
    if 'type' in kwargs.keys():
        type = kwargs['type']
        
    commentxml = getCommentXML(pid, type)
    return commentxml


''' countComment
    count the number of comment of one post
'''
def countComment(req, **kwargs):
    # get form variables
    pid = ''
    if 'id' in kwargs.keys():
        pid = kwargs['id']
    # get xml doc
    file = open('/home/bsft08/51158405/www/blog/api/comment.xml', 'r')
    data = file.read()
    file.close()    
    xmldoc = minidom.parseString(data)
    posts = xmldoc.getElementsByTagName("post")
    for post in posts:
        _id = getText(post.getElementsByTagName("id")[0].childNodes)
        if pid == _id:
            comments = post.getElementsByTagName("comment")
            return comments.length
    return 0


''' addComment
    add comment data to comment.xml
'''
def addComment(req, **kwargs):
    file = open('/home/bsft08/51158405/www/blog/api/comment.xml', 'r')
    data = file.read()
    file.close()    
    xmldoc = minidom.parseString(data)

    pid = ''
    user = ''
    content = '' 
    if 'id' in kwargs.keys():
        pid = kwargs['id']
    if 'user' in kwargs.keys():
        user = kwargs['user']
    if 'content' in kwargs.keys():
        content = kwargs['content']
    
    if not pid:
        return 'Must specify post ID.'
    if not user:
        return 'Please leave your name.'
    if not content:
        return 'Please leave your comment.'
    
    # create xml node for the new comment
    doc = Document()
    newComment = doc.createElement('comment')
    
    cid_n = doc.createElement('cid')
    cid_t = doc.createTextNode(str(uuid.uuid4()))
    cid_n.appendChild(cid_t)
    
    user_n = doc.createElement('user')
    user_t = doc.createTextNode(user)
    user_n.appendChild(user_t)
    
    time_n = doc.createElement('time')
    time_t = doc.createTextNode(strftime('%Y-%m-%d %H:%M:%S', localtime()))
    time_n.appendChild(time_t)
    
    content_n = doc.createElement('content')
    content_t = doc.createTextNode(content)
    content_n.appendChild(content_t)
    
    newComment.appendChild(cid_n)
    newComment.appendChild(user_n)
    newComment.appendChild(time_n)
    newComment.appendChild(content_n)

    try:
        posts = xmldoc.getElementsByTagName("post")
        exist = 'false'
        for post in posts:
            _id = getText(post.getElementsByTagName("id")[0].childNodes)
            if pid == _id:
                # add comment to a existing post
                post.appendChild(newComment)
                exist = 'true'
                break
                
        if exist == 'false':
            # add a new post node
            newPostNode = doc.createElement('post')
            id_n = doc.createElement('id')
            id_t = doc.createTextNode(pid)
            id_n.appendChild(id_t)
            newPostNode.appendChild(id_n)
            newPostNode.appendChild(newComment)
            bloglist = xmldoc.getElementsByTagName('BlogList')[0]
            bloglist.appendChild(newPostNode)
    except:
        return "Error!"
      
    # write xmldoc to an xml file
    file = open('/home/bsft08/51158405/www/blog/api/comment.xml', 'w')
    xmldoc.writexml(file, encoding='utf-8')
    file.close()
    return getText(newComment.getElementsByTagName("cid")[0].childNodes)


''' deleteComment
    delete a comment by its id
'''
def deleteComment(req, **kwargs):
    cid = ''
    if 'id' in kwargs.keys():
        cid = kwargs['id']
    file = open('/home/bsft08/51158405/www/blog/api/comment.xml', 'r')
    data = file.read()
    file.close()    
    xmldoc = minidom.parseString(data)
    comments = xmldoc.getElementsByTagName('comment')
    for comment in comments:
        _id = getText(comment.getElementsByTagName("cid")[0].childNodes)
        if cid == _id:
            # remove this comment node
            xmldoc.removeChild(comment)
            break
    # write xmldoc to an xml file
    file = open('/home/bsft08/51158405/www/blog/api/comment.xml', 'w')
    xmldoc.writexml(file, encoding='utf-8')
    file.close()
    return 'Comment deleted.'